/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.deployment.genericdao;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author elyjr
 */
public abstract class GenericDAO<T> {

    @PersistenceContext
    private EntityManager entityManager; 
    private Class<T> entity;

    public GenericDAO(Class<T> entity) {
        this.entity = entity;
    }

    public void save(T entity) {
        entityManager.persist(entity);
    }

    public void delete(T entity) {
        T entityToBeRemoved = entityManager.merge(entity);
        entityManager.remove(entityToBeRemoved);
    }

    public void update(T entity) {
        entityManager.merge(entity);
        entityManager.flush();
    }

    public T find(Long entityID) {
        return entityManager.find(entity, entityID);
    }

    public List<T> findAll() {
        return entityManager.createQuery("select e from " + entity.getSimpleName() + " e").getResultList();
    }

    public EntityManager getEntityManager() {
        return entityManager;
    }

    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }
}
